package com.kbtxwer.tmss;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.kbtxwer.tmss.URLsupport.*;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    //public TextView tv;
    long t1;
    JSONObject jo;
    JSONArray ja;
    ListView accountList;
    SimpleAdapter adapter;
    List<Map<String,String>> accounts;
    MyHandler handler = new MyHandler(new WeakReference<>(this));
    public static final int UPDATE_MAIN_PAGE = 0x123;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = System.currentTimeMillis();
        //tv = findViewById(R.id.tv);
        new Thread(()->{
            String str = GetPostUtil.sendGet("https://kbtxwer.gitee.io/blog/json","","GBK");
            Message msg = new Message();
            msg.what = UPDATE_MAIN_PAGE;
            msg.obj = str;
            handler.sendMessage(msg);
        }).start();
        accountList = findViewById(R.id.aList);
    }
    private class MyHandler extends Handler {
        private WeakReference<MainActivity> mainActivity;
        public MyHandler(WeakReference<MainActivity> mainActivity){
            this.mainActivity = mainActivity;
        }
        @Override
        public void handleMessage(Message msg){
            switch(msg.what){
                //处理主界面文本显示
                case UPDATE_MAIN_PAGE:{
                    //显示字符串，以检查内容是否被正确获取且无乱码
                    //mainActivity.get().tv.setText(msg.obj.toString());
                    //尝试以json格式进行解析
                    try {
                        jo = new JSONObject(msg.obj.toString());
                        ja = jo.getJSONArray("list");
                        //Toast.makeText(MainActivity.this,"json解析成功！",Toast.LENGTH_SHORT).show();
                        //初始化List
                        accounts = new ArrayList<>();
                        //将json数组转换成Map,并放入accounts中,以利用SimpleAdapter渲染
                        for(int i=0;i<ja.length();i++){
                            jo = (JSONObject) ja.get(i);
                            Map<String,String> map = new HashMap<>();
                            map.put("accountName",jo.getString("accountName"));
                            map.put("basicURL",jo.getString("basicURL"));
                            map.put("provider",jo.getString("provider"));
                            accounts.add(map);
                        }
                    } catch (JSONException e) {
                        Toast.makeText(MainActivity.this,"错误，当前字符串无法解析为json，具体内容为：" + msg.obj.toString(),Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                        //如果解析失败，提示错误信息后退出程序
                        try {
                            Thread.sleep(1000);
                            finish();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    }
                    //基本数据准备完毕，计算耗时
                    Toast.makeText(MainActivity.this,"准备就绪，耗时" + (System.currentTimeMillis()-t1) + "毫秒",Toast.LENGTH_LONG).show();
                    //完成适配器的设置
                    adapter = new SimpleAdapter(MainActivity.this,accounts,R.layout.article_provider_list,
                            new String[]{"accountName","provider","basicURL"},new int[]{R.id.account,R.id.provider,R.id.basicURL});
                    accountList.setAdapter(adapter);
                    //为每一个列表项设置单击事件，点击后应该跳转到下一个Activity
                    accountList.setOnItemClickListener((parent,view,position,id)-> {
                        TextView basicURL = view.findViewById(R.id.basicURL);
                        TextView accountName = view.findViewById(R.id.account);
                        //Toast.makeText(MainActivity.this,basicURL.getText().toString(),Toast.LENGTH_SHORT).show();
                        //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(basicURL.getText().toString()));
                        //startActivity(intent);
                        Intent intent = new Intent(MainActivity.this,Article_Detail.class);
                        intent.putExtra("basicURL",basicURL.getText().toString());
                        intent.putExtra("title",accountName.getText().toString());
                        startActivity(intent);
                    });
                }
            }
        }
    }
}
